<?php
/**
 * Created by PhpStorm.
 * User: i3538
 * Date: 2018-7-21
 * Time: 11:19
 */

require __DIR__. '/vendor/autoload.php';

use Grafika\Grafika;
use Grafika\Color;

$editor = Grafika::createEditor();
$imagePath = __DIR__ . '/images/';
$foregroundImg = $imagePath . 'foreground.png';
$foregroundImgInfo = getimagesize($foregroundImg);
$whiteColor = new Color('#ffffff');

function outPutPath($filename)
{
    return __DIR__ . '/output/' . $filename . '.jpg';
}

$holeInfo = [
    ['x' => 100, 'y' => 100, 'width' => 300, 'height' => 300],
    ['x' => 480, 'y' => 100, 'width' => 300, 'height' => 300],
    ['x' => 100, 'y' => 500, 'width' => 300, 'height' => 300],
    ['x' => 501, 'y' => 501, 'width' => 300, 'height' => 300],
];

$userImagesInfo = [
    ['pic' => '1.jpg', 'x' => 90, 'y' => 90, 'width' => 300, 'height' => 300, 'angle' => -10],
    ['pic' => '2.jpg', 'x' => 400, 'y' => 100, 'width' => 400, 'height' => 300, 'angle' => 30],
    ['pic' => '3.jpg', 'x' => 100, 'y' => 400, 'width' => 477, 'height' => 400, 'angle' => -10],
    ['pic' => '4.jpg', 'x' => 300, 'y' => 400, 'width' => 600, 'height' => 500, 'angle' => -40],
];

$editor->open($product, $foregroundImg);


foreach ($userImagesInfo as $index => $userImg)
{
    $step = 0;
    $hole = $holeInfo[$index];
    //创建一个白色画布
    $canvas = Grafika::createBlankImage($foregroundImgInfo[0], $foregroundImgInfo[1]);
    $editor->fill($canvas, $whiteColor);

    $editor->open($editingUserImg, $imagePath . $userImg['pic']);
    //旋转之
//    $editor->rotate($editingUserImg, $userImg['angle'], $whiteColor);
//    $editor->save($editingUserImg, outPutPath("{$index}_{$step}_user_img_after_rotate"));
//    $step++;
    //缩放之
    $editor->resize($editingUserImg, $userImg['width'], $userImg['height']);
    $editor->save($editingUserImg, outPutPath("{$index}_{$step}_user_img_after_resize"));
    $step++;
    //将处理完的图片放到画布上边
    $editor->blend($canvas, $editingUserImg, 'normal', 1, 'top-left', $userImg['x'], $userImg['y']);
    $editor->save($canvas, outPutPath("{$index}_{$step}_canvas_blend_user_img_after_resize"));
    $step++;
    //对画布进行裁切，拿出需要的部分。
    $editor->crop($canvas, $hole['width'], $hole['height'], 'top-left', $hole['x'], $hole['y']);
    $editor->save($canvas, outPutPath("{$index}_{$step}_user_img_crop_from_blend_canvas"));
    $step++;
    //将最终结果放到作品上
    $editor->blend($product, $canvas, 'normal', 1, 'top-left', $hole['x'], $hole['y']);
    $editor->save($product, outPutPath("{$index}_product"));
    die;
}
